"""
配置管理工具
处理配置文件的读取和验证
"""

import json
import os
import logging
from typing import Dict, Any


class ConfigManager:
    """配置管理器"""

    def __init__(self, config_path: str = "config/config.json"):
        self.config_path = config_path
        self.config: Dict[str, Any] = {}
        self.logger = self._setup_logger()

    def _setup_logger(self) -> logging.Logger:
        """设置日志记录器"""
        logger = logging.getLogger("ConfigManager")
        if not logger.handlers:
            handler = logging.StreamHandler()
            formatter = logging.Formatter(
                "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
            )
            handler.setFormatter(formatter)
            logger.addHandler(handler)
            logger.setLevel(logging.INFO)
        return logger

    def load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        try:
            if not os.path.exists(self.config_path):
                self.logger.error(f"配置文件不存在: {self.config_path}")
                raise FileNotFoundError(f"配置文件不存在: {self.config_path}")

            with open(self.config_path, "r", encoding="utf-8") as f:
                self.config = json.load(f)

            # 验证配置
            self._validate_config()

            self.logger.info("配置文件加载成功")
            return self.config

        except json.JSONDecodeError as e:
            self.logger.error(f"配置文件格式错误: {e}")
            raise
        except Exception as e:
            self.logger.error(f"加载配置文件失败: {e}")
            raise

    def save_config(self, config: Dict[str, Any] = None) -> None:
        """保存配置文件"""
        try:
            if config is not None:
                self.config = config

            with open(self.config_path, "w", encoding="utf-8") as f:
                json.dump(self.config, f, ensure_ascii=False, indent=2)

            self.logger.info("配置文件保存成功")

        except Exception as e:
            self.logger.error(f"保存配置文件失败: {e}")
            raise

    def _validate_config(self) -> None:
        """验证配置文件完整性"""
        required_sections = ["user", "ticket", "mobile", "retry", "notification"]

        for section in required_sections:
            if section not in self.config:
                raise ValueError(f"配置文件缺少必要部分: {section}")

        # 验证用户配置
        user_config = self.config["user"]
        if not user_config.get("username") or not user_config.get("password"):
            self.logger.warning("用户名或密码未配置")

        # 验证票务配置
        ticket_config = self.config["ticket"]
        if not ticket_config.get("event_name"):
            self.logger.warning("演出名称未配置")
        if not ticket_config.get("event_url"):
            self.logger.warning("演出链接未配置")

        # 验证移动端配置
        mobile_config = self.config["mobile"]
        if not mobile_config.get("app_package"):
            self.logger.warning("App包名未配置，使用默认值")
            self.config["mobile"]["app_package"] = "cn.damai"

    def get_user_config(self) -> Dict[str, Any]:
        """获取用户配置"""
        return self.config.get("user", {})

    def get_ticket_config(self) -> Dict[str, Any]:
        """获取票务配置"""
        return self.config.get("ticket", {})

    def get_mobile_config(self) -> Dict[str, Any]:
        """获取移动端配置"""
        return self.config.get("mobile", {})

    def get_retry_config(self) -> Dict[str, Any]:
        """获取重试配置"""
        return self.config.get("retry", {})

    def get_notification_config(self) -> Dict[str, Any]:
        """获取通知配置"""
        return self.config.get("notification", {})

    def update_user_info(
        self,
        username: str,
        password: str,
        phone: str = "",
        real_name: str = "",
        id_card: str = "",
    ) -> None:
        """更新用户信息"""
        if "user" not in self.config:
            self.config["user"] = {}

        self.config["user"].update(
            {
                "username": username,
                "password": password,
                "phone": phone,
                "real_name": real_name,
                "id_card": id_card,
            }
        )

        self.save_config()
        self.logger.info("用户信息已更新")

    def update_ticket_info(
        self,
        event_name: str,
        event_url: str,
        session_index: int = 0,
        price_index: int = 0,
        ticket_num: int = 1,
    ) -> None:
        """更新票务信息"""
        if "ticket" not in self.config:
            self.config["ticket"] = {}

        self.config["ticket"].update(
            {
                "event_name": event_name,
                "event_url": event_url,
                "session_index": session_index,
                "price_index": price_index,
                "ticket_num": ticket_num,
            }
        )

        self.save_config()
        self.logger.info("票务信息已更新")
